const express = require("express");
const router = express.Router();
const passport = require("passport");
const Address = require("../../../models/Address");
const errorHandler = require("../../../middlewares/errorHandler");

// Middleware to protect routes
const auth = passport.authenticate("jwt", { session: false });

// @route  GET api/address/test
router.get("/test", (req, res) => res.json({ msg: "address works" }));

// @route  POST api/address/add
// @desc   添加新的收货地址
// @access Private
router.post("/add", auth, async (req, res) => {
  try {
    if (req.body.defaultAddress) {
      // 检查是否已经存在默认地址，将其取消默认状态
      await Address.updateMany(
        { user: req.user.id, defaultAddress: true },
        { defaultAddress: false }
      );
    }

    const newAddress = new Address({
      user: req.user.id,
      ...req.body,
    });

    const address = await newAddress.save();
    res.status(200).json({ success: true, data: address });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  GET api/address
// @desc   获取当前用户的所有收货地址
// @access Private
router.get("/", auth, async (req, res) => {
  try {
    const addresses = await Address.find({ user: req.user.id });
    res
      .status(200)
      .json({ success: true, count: addresses.length, data: addresses });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  GET api/address/:id
// @desc   获取单个收货地址
// @access Private
router.get("/:id", auth, async (req, res) => {
  try {
    const address = await Address.findOne({
      _id: req.params.id,
      user: req.user.id,
    });
    if (!address) {
      return res.status(404).json({ success: false, error: "未找到数据" });
    }
    res.status(200).json({ success: true, data: address });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  POST api/address/edit
// @desc   编辑收货地址
// @access Private
router.post("/edit", auth, async (req, res) => {
  try {
    const { _id, defaultAddress, ...updateData } = req.body;
    if (defaultAddress) {
      // 检查是否已经存在默认地址，将其取消默认状态
      await Address.updateMany(
        { user: req.user.id, defaultAddress: true },
        { defaultAddress: false }
      );
    }
    const address = await Address.findOneAndUpdate(
      { _id, user: req.user.id },
      { ...updateData, defaultAddress },
      { new: true }
    );
    if (!address) {
      return res.status(404).json({ success: false, error: "未找到数据" });
    }
    res.status(200).json({ success: true, data: address });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  DELETE api/address/delete
// @desc   删除收货地址
// @access Private
router.delete("/delete", auth, async (req, res) => {
  try {
    const { _id } = req.body;
    const address = await Address.findOneAndRemove({ _id, user: req.user.id });
    if (!address) {
      return res.status(404).json({ success: false, error: "未找到内容" });
    }
    res.status(200).json({ success: true, data: address });
  } catch (err) {
    errorHandler(res, err);
  }
});

module.exports = router;
